package com.bscc.admin.user;

import com.bscc.common.model.Role;
import com.bscc.common.model.User;
import com.bscc.common.utils.MD5Utils;
import com.bscc.admin.role.RoleService;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;

public class UserService
{
    /**
     * 所有的 dao 对象也放在 Service 中
     */
    private static final User dao = new User().dao();

    static RoleService roleService = new RoleService();

    public Page<User> paginate(int pageNumber, int pageSize)
    {
        return dao.paginate(pageNumber, pageSize, "SELECT *", "FROM bw_user ORDER BY id ASC");
    }

    public List<User> findList()
    {
        return dao.find("SELECT id,account,name FROM bw_user ORDER BY sort");
    }

    public List<User> findListForWeb()
    {
        return dao.find("SELECT id,account,name FROM bw_user WHERE is_show=1 ORDER BY sort");
    }

    public User findById(int id)
    {
        User user = dao.findById(id);
        if(null != user && null != user.getRole() && user.getRole() != 0)
        {
            Role role = roleService.findById(user.getRole());
            user.setRoleName(role.getName());
        }
        return user;
    }

    public void deleteById(int id)
    {
        dao.deleteById(id);
    }

    public void save(User user)
    {
        if(StringUtils.isNotBlank(user.getPassword()))
            user.setPassword(MD5Utils.getMD5Twice(user.getPassword()));
        else
            user.setPassword(MD5Utils.getMD5Twice("123456"));
        user.save();
    }

    public void update(User user)
    {
        User tmp = dao.findById(user.getId());

        if(StringUtils.isNotBlank(user.getPassword()) && !user.getPassword().equals(tmp.getPassword()))
            user.setPassword(MD5Utils.getMD5Twice(user.getPassword()));

        user.update();
    }

    public User verifySignIn(User user)
    {
        User thisUser = findByAccount(user.getAccount());
        if(null != thisUser && MD5Utils.getMD5Twice(user.getPassword()).equals(thisUser.getPassword()) && null != thisUser.getRole()
                &&(thisUser.getRole() == 1 || (null != thisUser.getMenuList() && thisUser.getMenuList().size() > 0)))
        {
            thisUser.setLastLoginDate(new Date());
            thisUser.update();
            return thisUser;
        }
        else
            return null;
    }

    public User findByAccount(String account)
    {
        List<User> userList = dao.find("SELECT * FROM bw_user WHERE account=?", account);
        if(userList != null && userList.size() == 1)
        {
            User user = userList.get(0);
            if(null != user.getRole())
                user.setMenuList(roleService.findById(user.getRole()).getMenuList());
            return user;
        }
        else
            return null;
    }
}
